import AppFooter from "@/components/layout/AppFooter";
import styled from "styled-components";
import BannerInfo from "./components/BannerInfo";
import { useEffect, useMemo, useRef, useState } from "react";
import { useParams } from "react-router-dom";
import { api } from "@/api";
import { convertImgUrl } from "@/utils/MyFun";
import { Card, Col, Row } from "antd";
import ReactMarkdown from "react-markdown"; //引入
import remarkGfm from "remark-gfm"; // 划线、表、任务列表和直接url等的语法扩展
import rehypeRaw from "rehype-raw"; // 解析标签，支持html语法
import SyntaxHighlighter from "react-syntax-highlighter";
import { tomorrowNightEighties } from "react-syntax-highlighter/dist/esm/styles/hljs";
import "github-markdown-css";
import Catalogue from "./components/Catalogue";
import LatestList from "./components/LatestList";
import Copyright from "./components/Copyright";
import Reward from "./components/Reward";
import Forward from "./components/Forward";
import LastNext from "./components/LastNext";
import Recommend from "./components/Recommend";
import Comment from "@/components/comment/Comment";

const Styled = styled.div`
  width: 100%;
  .banner {
    height: 90rem;

    display: flex;
    align-items: center;
    justify-content: center;
  }
  @media (min-width: 1024px) {
    .banner {
      height: 100rem;
    }
  }
  .t-h {
    width: 100%;
  }
  .card-fade-up {
    animation: card-fade-up-anim 0.6s;
  }
  @keyframes card-fade-ip-anim {
    0% {
      opacity: 0;
      filter: alpha(opacity=0);
      transform: translateY(50px);
    }

    100% {
      opacity: 1;
      filter: none;
      transform: translateY(0);
    }
  }
  .card-fix {
    position: sticky !important;
    top: 15rem !important;
  }
`;

const ArticleDetail = () => {
  const { id } = useParams();
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState({
    id: 0,
    title: "",
    content: "",
    created_at: "",
    updated_at: "",
    like_count: 0,
    view_count: 0,
    comment_count: 0,
    img: "",
    newest_articles: [],
    tags: [],
    category: {},
    next_article: {},
    last_article: {},
    recommend_articles: [],
  });
  const previewRef = useRef();

  const styleVal = useMemo(() => {
    return data.img
      ? {
          background: `url('${convertImgUrl(
            data.img
          )}') center center / cover no-repeat`,
        }
      : { background: ` rgba(0,0,0,0.1) center center / cover no-repeat` };
  }, [data.img]);

  useEffect(() => {
    //根据id获取文章信息
    (async () => {
      try {
        const res = await api.getArticleDetail(+id);
        setData(res.data);
      } catch (error) {
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  useEffect(() => {
    const link = document.createElement("link");
    link.type = "text/css";
    link.rel = "stylesheet";
    link.href =
      "https://cdn.bootcss.com/github-markdown-css/2.10.0/github-markdown.min.css";
    document.head.appendChild(link);
  }, []);

  return (
    <Styled>
      {/* 头部 */}
      <div className="banner banner-fade-down" style={styleVal}>
        {!loading ? <BannerInfo article={data} /> : null}
      </div>
      {/* 文章内容 */}
      <main
        className="flex"
        style={{
          width: "100%",
          padding: "10rem 50rem",
          justifyContent: "center",
        }}
      >
        <Row className="t-h card-fade-up" gutter={10}>
          <Col xl={16} xs={24}>
            <Card hoverable style={{ cursor: "auto" }}>
              {/* 文章内容 */}
              <ReactMarkdown
                className="markdown-body"
                children={data.content}
                remarkPlugins={[remarkGfm]}
                rehypePlugins={[rehypeRaw]}
                components={{
                  code({ node, inline, className, children, ...props }) {
                    const match = /language-(\w+)/.exec(className || "");
                    return !inline && match ? (
                      <SyntaxHighlighter
                        children={String(children).replace(/\n$/, "")}
                        style={tomorrowNightEighties}
                        language={match[1]}
                        PreTag="div"
                        {...props}
                      />
                    ) : (
                      <code className={className} {...props}>
                        {children}
                      </code>
                    );
                  },
                }}
              />
              {/* 版权申明 */}
              <Copyright />
              {/* 标签转发 */}
              <Forward tagList={data.tags} />
              {/* 点赞，打赏 */}
              <Reward articleId={data.id} likeCount={data.like_count} />
              {/* 上一篇，下一篇 */}
              <LastNext
                lastArticle={data.last_article}
                nextArticle={data.next_article}
              />
              {/* 推荐文章 */}
              <Recommend recommendArticle={data.recommend_articles} />
              {/* 分割线 */}
              <hr
                style={{
                  borderStyle: "dashed",
                  borderWidth: "2px",
                  borderColor: "rgba(210, 235, 253, 1)",
                  marginTop: "3.75rem",
                  marginBottom: "5rem",
                }}
              />
              {/* 文章评论 */}
              <Comment type={1} />
            </Card>
          </Col>
          <Col xl={6} xs={0}>
            <Card hoverable className="card-fix">
              {/* 目录 */}
              {!loading ? <Catalogue content={data.content} /> : null}
              {/* 最新文章 */}
              <LatestList articleList={data.newest_articles} />
            </Card>
          </Col>
        </Row>
      </main>
      {/* 底部 */}
      <footer>
        <AppFooter />
      </footer>
    </Styled>
  );
};

export default ArticleDetail;
